package instantHelper.ClosedMode;

import instantHelper.Models.CustomHttpClient;
import instantHelper.NormalMode.MyLocationListener;
import instantHelper.Raceway.DbHelper;
import instantHelper.Raceway.FTPHelper;
import instantHelper.Raceway.InstantHelperConstant;
import instantHelper.Raceway.R;
import instantHelper.Raceway.SettingsUtil;
import instantHelper.Raceway.Synchronize;

import java.io.*;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.*;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;

public class ClosedModeAudioRecorder extends Activity {

	public MediaRecorder mrec = null;
	private String androidId;
	private String requestId;
	File audiofile;
	String fileNameForFTP;
	int maxDuration;

	ArrayList<String> audioPaths = new ArrayList<String>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.closedmode_audio);

		androidId = SettingsUtil.getAndroidID(getApplicationContext());
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			requestId = extras.getString("requestId");
		}
		maxDuration = Integer.parseInt(SettingsUtil
				.getAudioMaximumDuration(getApplicationContext()));
		MyLocationListener.getGPSData(getApplicationContext(), androidId,
				requestId);
		sendAudios();
	}

	private void sendAudios() {

		for (int i = 0; i < 5; i++) {
			try {
				mrec = new MediaRecorder();
				mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
				mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
				mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
				String fileName = createAudioPaths("audio_" + requestId + "_"
						+ i);
				mrec.setOutputFile(fileName);
				mrec.prepare();
				mrec.start();
				recorderRelease();
				String result = sendAudioRequestToCentralAPP(fileName);
				if (result.equals("successfull")) {
					boolean issend = FTPHelper
							.sendToServer(fileName, "audios/");
					if (!issend) {
						ContentValues contentValues = new ContentValues();
						Date time = new Date();
						contentValues.put(
								InstantHelperConstant.DB_DIRECTORY_DATE,
								time.toString());
						contentValues.put(
								InstantHelperConstant.DB_DIRECTORY_ISSEND, "0");
						contentValues.put(
								InstantHelperConstant.DB_DIRECTORY_PATH,
								fileName);
						contentValues.put(
								InstantHelperConstant.DB_DIRECTORY_REQUEST_ID,
								requestId);
						contentValues.put(
								InstantHelperConstant.DB_DIRECTORY_TYPE,
								"audio");
						// update
						DbHelper myDbHelper1 = new DbHelper(this);
						SQLiteDatabase db1 = myDbHelper1.getWritableDatabase();
						db1.insert(InstantHelperConstant.DB_DIRECTORY_TABLE,
								null, contentValues);

					} else {
						if (SettingsUtil
								.getDeleteDataControl(getApplicationContext())) {
							SettingsUtil.deleteFile(fileName);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		finish();
	}

	private void recorderRelease() {
		try {
			Thread.sleep(maxDuration * 1000);
			mrec.stop();
			mrec.release();

		} catch (Exception e) {
		}
	}

	protected String createAudioPaths(String filePath) {
		String fileName = "ihcenterapp/audios/" + filePath + ".mp4";
		fileNameForFTP = filePath + ".mp4";
		fileName = sanitizePath(fileName);
		// make sure the directory we plan to store the recording in exists
		File directory = new File(fileName).getParentFile();
		if (!directory.exists() && !directory.mkdirs()) {
			try {
				throw new IOException("Path to file could not be created.");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		audioPaths.add(fileName);
		return fileName;
	}

	protected String sanitizePath(String path) {
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		if (!path.contains(".")) {
			path += ".mp4";
		}
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ path;
	}

	private String sendAudioRequestToCentralAPP(String fileName)
			throws IllegalStateException, IOException, URISyntaxException {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/newAudio";

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("audioPath", fileNameForFTP));
		postParameters.add(new BasicNameValuePair("requestId", requestId));
		postParameters.add(new BasicNameValuePair("androidId", androidId));
		String response = null;
		String result = "";
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			String res = response.toString();
			JSONObject jObject = new JSONObject(res);
			result = jObject.getString("result");
			Context context = getApplicationContext();
		} catch (Exception e) {
		}
		return result;
	}

	protected void stopRecording() {
		mrec.stop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mrec.release();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mrec.release();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mrec.release();
	}

}